/*******************************************************************************
 * Copyright 2014 United States Government as represented by the
 * Administrator of the National Aeronautics and Space Administration.
 * All Rights Reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package gov.nasa.arc.spife.core.plan.rules.view;

import gov.nasa.arc.spife.core.plan.rules.view.columns.IPlanRulesSortableColumn;
import gov.nasa.ensemble.dictionary.ERule;

import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;

public class PlanRulesViewerComparator extends ViewerComparator {

	private IPlanRulesSortableColumn key = null;
	private boolean reverse = false;
	
	public IPlanRulesSortableColumn getKey() {
		return key;
	}

	public void setKey(IPlanRulesSortableColumn key) {
		this.key = key;
	}

	public boolean isReverse() {
		return reverse;
	}

	public void setReverse(boolean reverse) {
		this.reverse = reverse;
	}
	
	@Override
	public int compare(Viewer viewer, Object e1, Object e2) {
		return (reverse ? -1 : 1) * order(viewer, e1, e2);
	}

	private int order(Viewer viewer, Object e1, Object e2) {
		if ((e1 instanceof RuleGroup) && (e2 instanceof RuleGroup)) {
			RuleGroup group1 = (RuleGroup) e1;
			RuleGroup group2 = (RuleGroup) e2;
			String value1 = group1.getLabel();
			String value2 = group2.getLabel();
			return String.CASE_INSENSITIVE_ORDER.compare(value1, value2);
		}
		if ((e1 instanceof ERule) && (e2 instanceof ERule)) {
			ERule o1 = (ERule) e1;
			ERule o2 = (ERule) e2;
			if (key == null) {
				return PlanRuleComparator.INSTANCE.compare(o1, o2);
			}
			return key.compare(o1, o2);
		}
		return super.compare(viewer, e1, e2);
	}
	
}
